package com.zgc.web.action;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.zgc.domain.User;
import com.zgc.service.IUserService;
@Controller
@Scope("prototype")
public class UserAction extends ActionSupport implements ModelDriven<User>{
	
	private User user = new User();
	@Resource
	private IUserService userService;
	//获取前台验证码
	private String checkcode;
	
	public void setCheckcode(String checkcode) {
		this.checkcode = checkcode;
	}
	//注册方法
	public String regist() {
		userService.regist(user);
		return SUCCESS;
	}
	//登录方法
	public String login(){
		//从session中获取验证码
		String validateCode = (String) ServletActionContext.getRequest().getSession().getAttribute("key");
		//确定验证码是否正确
		if (StringUtils.isBlank(checkcode) || !checkcode.equals(validateCode)) {
			//验证码不正确
			this.addActionError("验证码输入错误!");
			return LOGIN;
		}else {
			//验证码正确
			//用户名密码为空
			if (StringUtils.isBlank(user.getUsername()) || StringUtils.isBlank(user.getPassword())) {
				this.addActionError("用户名或者密码不能为空");
				return LOGIN;
			}else {
				//用户名和密码非空
				User loginUser = userService.login(user.getUsername(),user.getPassword());
				if (loginUser==null) {
					this.addActionError("用户名或密码不正确");
					return LOGIN;
				}else {
					ServletActionContext.getRequest().getSession().setAttribute("loginUser", loginUser);
					return SUCCESS;
				}
			}
			
		}
	}
	//退出登录方法
	public String logout() {
		ServletActionContext.getRequest().getSession().invalidate();
		return SUCCESS;
	}
	public User getModel() {
		return user;
	}
	
	
}
